#! /usr/bin/env ruby

require 'json'

unless (ARGV[0] && ARGV[1])
   puts "Usage: connect-to <build-label> <role-name> [<user>]"
   exit 1
end

label=ARGV[0]
role=ARGV[1]
user=ARGV[2] ? ARGV[2] : "root"
vmconf_file = "deployment_data/vmconfig-#{label}.json"
if (File.exists?(vmconf_file))
   vmconfig = JSON.parse(File.read(vmconf_file))
else 
   puts "There is no vm config file for the buildlabel #{label}"
   exit 1
end

vmconfig.each { |vm| 
   if (vm['snaprole'].downcase == role.strip.downcase) 
      ip = vm['ip']
      puts "Connecting to #{ip}"
      cmd="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i ws_data/workstation-key #{user}@#{ip}"
      puts "executing: #{cmd}"
      system(cmd)
      exit 0
   end
}

puts "VM with role #{role} was not found. "